package cn.com.callback

import cn.com.kh.KHUtil
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.PropertiesUtil;
import cn.com.elite.Util;
import java.text.SimpleDateFormat
import java.util.Map;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

/**
 *
 * @author msjykf* 批次数据提交到安正数据中心跑数
 *{"batch_id":"","template_id":"","requesttype": 1}* batch_id：批次号;template_id:短信模板ID;requesttype:请求类型 1定时任务调度 2动态页面调度
 *
 *
 */
public class SmsBatchRequest implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(SmsBatchRequest.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        try {
            def jsonbody = Util.getRequestBody(request, 'utf-8'); //获取报文
            if (jsonbody.equals("")) {
                return "{\"msg\": \"未获取到入参报文！\",\"code\": -2}"
            };
            JSONObject obj = JSONObject.fromObject(jsonbody); //解析报文
            def sms_id = Util.filterForObject(obj.get("template_id")); //模板id
            if (sms_id.equals("")) {
                return "{\"msg\": \"短信模板ID不能为空！\",\"code\": -2}"
            };
            def requesttype = Util.filterForObject(obj.get("requesttype"));
            String requestdesc = Util.filterForObject(obj.get("requestdesc"));
            String old_batch_id = Util.filterForObject(obj.get("old_batch_id"));
            if (requesttype.equals("")) {
                return "{\"msg\": \"requesttype参数不能为空！\",\"code\": -2}"
            };
            def batch_id = ""; //批次号
            def procflag = ""; //安正短信模板ID
            def content = ""; //短信内容
            def tbname = ""; //客户分组表名
            def datafrom = ""; //数据来源：0安正接口 1客户分组
            def params = ""; //控制参数
            def params_5 = ""; //控制参数_持有基金每日净值按周
            def PI_TPLID = ""; //old短信模板ID
            def i = 0;
            def smap = eliteBean.chaxun_sql("select st.c_taskcode,st.content,st.datafrom,ma.customergroup_tablename,pf.totalid,pf.net_value from sms_template_search st left join multimediaaddressee ma on st.relation_id=ma.doctemplate_id left join preferences pf on st.relation_id=pf.doctemplate_id where st.sms_id='" + sms_id + "' and st.datafrom is not null", "dataSource");
            def smap1 = eliteBean.chaxun_sql("SELECT PI_TPLID FROM  preferences WHERE DOCTEMPLATE_ID='" + sms_id + "'", "dataSource");
            if (smap.size() == 0) {
                return "{\"msg\": \"无效的短信模板！\",\"code\": -2}"
            } else {
                procflag = Util.filterForObject(smap[0].get("c_taskcode"));
                content = Util.filterForObject(smap[0].get("content"));
                tbname = Util.filterForObject(smap[0].get("customergroup_tablename"));
                datafrom = Util.filterForObject(smap[0].get("datafrom"));
                params = Util.filterForObject(smap[0].get("totalid"));
                params_5 = Util.filterForObject(smap[0].get("net_value"));
                try {

                    PI_TPLID = Util.filterForObject(smap1[0].get("PI_TPLID"));
                } catch (Exception e) {
                    log.debug("ErrorMessage:", e);
                }
            };
            log.debug("界面中配置的控制totalid内容" + params);
            if (datafrom.equals("")) {
                return "{\"msg\": \"数据来源不能为空！\",\"code\": -2}"
            } else if (datafrom.equals("1") && tbname.equals("")) {
                return "{\"msg\": \"客户分组不能为空！\",\"code\": -2}"
            } else if (datafrom.equals("1")) {
                StringBuffer sb = new StringBuffer();
                String[] temp = tbname.split(",");
                for (i = 0; i < temp.length; i++) {
                    switch (i) {
                        case 0:
                            sb.append("'" + temp[i] + "'");
                            break;
                        default:
                            sb.append(",'" + temp[i] + "'");
                            break;
                    }
                };
                smap = eliteBean.chaxun_sql("select min(nvl(gs.acceptstate,1)) as state from customer_group_list gl left join customer_group_synchis gs on gl.lastrunbatch_id=gs.batch_id where gl.customergroup_tablename in (" + sb + ")", "dataSource");
                if (Util.filterForObject(smap[0].get("state")).equals("0")) {
                    return "{\"msg\": \"客户分组数据未执行完！\",\"code\": -2}"
                };
            };
            if (requesttype.equals("1")) {
                batch_id = Util.filterForObject(obj.get("batch_id"));
                if (batch_id.equals("")) {
                    return "{\"msg\": \"批次号不能为空！\",\"code\": -2}"
                } else if (procflag.equals("")) {
                    return "{\"msg\": \"调度任务ID不能为空！\",\"code\": -2}"
                }
            } else if (requesttype.equals("2")) {
                smap = eliteBean.chaxun_sql("select customgetid('MS') as batch_id from dual", "dataSource");
                log.debug("调用函数获取批次名：" + smap);

                batch_id = smap[0].get("batch_id");
                log.debug("解析获取批次名：" + batch_id);
                eliteBean.update("Insert Into Sms_Send_Batch (Batch_Id, Sms_Id, Comments) Values ('" + batch_id + "', '" + sms_id + "', '" + requestdesc + "')", "dataSource");

                // requestdesc非空且为[#系统自动创建(原批次超时废弃)] 为失败批次自动重发,记录日志表避免自动生成的批次失败后也会再次重发
                if (!KHUtil.isNull(requestdesc) && requestdesc == "#系统自动创建(原批次超时废弃)") {
                    eliteBean.update("Insert Into Sys_Deal_Log (Rec_Guid, Rec_Id, Old_Rec_Id, Deal_Type, Deal_Desc, Createdate, State, Comments, Deal_Times, Limit_Times) Values (Sys_Guid(), '" + batch_id + "','" + old_batch_id + "', 'SmsBatchAutoTask', '#自动将安正超时未返回批次废弃重发', Sysdate, 1, 'requestdesc非空且为[#系统自动创建(原批次超时废弃)] 为失败批次自动重发,记录日志表避免自动生成的批次失败后也会再次重发', 1, 1)", "dataSource");
                }

            };

            // 检查批次是否有调用次数控制表
            List getLogHis = eliteBean.chaxun_sql("Select Rec_Guid, Deal_Times From Sys_Deal_Log Where Deal_Type = 'SmsBatchRequest' And Rec_Id = '" + batch_id + "'", "dataSource");
            if (getLogHis.size() <= 0) {
                eliteBean.update("Insert Into Sys_Deal_Log (Rec_Guid, Rec_Id, Deal_Type, Deal_Desc, Createdate, State, Comments, Deal_Times) Values (Sys_Guid(), '" + batch_id + "', 'SmsBatchRequest', '批次调用次数控制', Sysdate, 0, '/', 0)", "dataSource");
            }

            if (datafrom.equals("0")) {
                //安正接口取数据
                PropertiesUtil properties = new PropertiesUtil();
                def ibqurl = properties.readValue("ibqurl"); //获取webservice接口地址
                def appid = properties.readValue("appid"); //获取appId
                def charset = "utf-8"; //设置字符集
                def timeout = 100000; //设置请求超时时间
                if (params.equals("")) {
                    params = """<params>
							<isOutDirectionParam>false</isOutDirectionParam>
							<name>PI_DK_SYSTEM</name>
							<value>*</value>
					</params>
 					<params>
							<isOutDirectionParam>false</isOutDirectionParam>
							<name>PI_AGENCYNO</name>
							<value>*</value>
					</params>
					<params>
							<isOutDirectionParam>false</isOutDirectionParam>
							<name>PI_SK_AGENCY</name>
							<value>*</value>
					</params>
 					<params>
							<isOutDirectionParam>false</isOutDirectionParam>
							<name>PI_BK_PRODUCT</name>
							<value>*</value>
					</params>
					<params>
							<isOutDirectionParam>false</isOutDirectionParam>
							<name>PI_SK_DATE</name>
							<value>*</value>
					</params>""";
                };
                //判断是否为持有基金每日净值按周/且是否为每周最后一个工作日
                if (procflag == '0001') {
                    String date = '';
                    def smapdate = eliteBean.chaxun_sql("select (SELECT to_char(SK_DATE,'YYYY-MM-DD') FROM preferences WHERE doctemplate_id='" + sms_id + "') as SK_DATE from dual", "dataSource");
                    if (smapdate.size() > 0) {
                        date = smapdate[0].get("SK_DATE");
                        log.debug("当时间为：" + date);
                        if (date == null || date == '') {
                            Calendar cal = Calendar.getInstance();
                            def year = cal.get(Calendar.YEAR);
                            def month = cal.get(Calendar.MONTH) + 1;
                            def day = cal.get(Calendar.DAY_OF_MONTH);
                            date = year + "-" + month + "-" + day;
                        }
                        log.debug("当时间为：" + date + ",当前为周：" + dayForWeek(date));
                    }
                    def smapdatetype = eliteBean.chaxun_sql("select case when   max(case  when date_d >= trunc(to_date('" + date + "','yyyy-mm-dd'), 'd') + 1 and date_d <= trunc(to_date('" + date + "','yyyy-mm-dd'), 'd') + 7 and workflag = 1 then date_d else null end) =to_date（'" + date + "','yyyy/mm/dd') then 1 else 0 end  as weekdatetype from c_calendar", "dataSource");
                    log.debug("查询smapdatetype：" + smapdatetype);
                    String weekdatetype = '';
                    if (smapdatetype.size() > 0) {
                        weekdatetype = smapdatetype[0].get("weekdatetype");
                        log.debug("weekdatetype标示1按周，0按天：" + weekdatetype);

                        //本周最后一个工作日，如果是则按周照拿params,否则按天拿params_5
                        if (procflag == '0001' && weekdatetype != '1') {
                            log.debug("按天！");
                            params = params_5;
                        }
                    }
                }
                log.debug("调用安正接口时传入的params内容" + params);
                def xmlbody = """<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
					<SOAP-ENV:Body>
						<m:executeProcedure xmlns:m="http://service.web.server.ua.businessmatrix.com/">
							<appId>""" + appid + """</appId>
								<name>s-P_SMS_INFO</name>
								<params>
									<isOutDirectionParam>false</isOutDirectionParam>
									<name>PI_BATCHID</name>
									<value>""" + batch_id + """</value>
							</params>
							<params>
								<isOutDirectionParam>false</isOutDirectionParam>
								<name>PI_SMSID</name>
								<value>""" + sms_id + """</value>
								</params>
								<params>
									<isOutDirectionParam>false</isOutDirectionParam>
									<name>PI_SMS_CONTENT</name>
									<value>""" + content + """</value>
							</params>
							<params>
								<isOutDirectionParam>false</isOutDirectionParam>
								<name>PI_PROCFLAG</name>
								<value>""" + procflag + """</value>
								</params>
								""" + params + """
								<params>
								<isOutDirectionParam>false</isOutDirectionParam>
								<name>PI_TPLID</name>
								<value>""" + PI_TPLID + """</value>
								</params>
						</m:executeProcedure>
					</SOAP-ENV:Body>
				</SOAP-ENV:Envelope>""";
                log.debug("调用安正接口时传入的xmlbody内容" + xmlbody);
                String result = "";
                String exceptionInfo = "";
                try {
                    result = Util.callWebService(ibqurl, xmlbody, charset, "", timeout);
                    log.debug("调用安正接口时返回的result原始内容" + result);
                } catch (Exception e) {
                    exceptionInfo = "调用安正接口时出现异常:" + e.getMessage();
                    log.warn(exceptionInfo);
                }

                String logState = 0;
                String logComments = "0";
                if (!KHUtil.isNull(result)) {
                    logState = 1;
                    logComments = "请求接口成功";
                    String[] data = new String[2];
                    data[0] = "update sms_send_batch set state=0,inputmsg='" + xmlbody + "',outputmsg='" + result + "',requesttime=sysdate where batch_id='" + batch_id + "'";
                    data[1] = "update sms_template set lastsendtime=sysdate,batch_no='" + batch_id + "' where sms_id='" + sms_id + "'";
                    int[] dataresult = eliteBean.updateBatch(data, "dataSource");

                    return "{\"msg\": \"请求接口成功！\",\"code\": 1}";
                } else {
                    logState = -1;
                    logComments = "请求接口失败";
                    String[] data = new String[3];
                    data[0] = "update sms_send_batch set state=-1,inputmsg='" + xmlbody + "',outputmsg='" + result + "',requesttime=sysdate where batch_id='" + batch_id + "'";
                    data[1] = "Update Sms_Template Set Lastsendtime = Sysdate, Batch_No = '" + batch_id + "' Where Sms_Id = '" + sms_id + "'";
                    data[2] = "Update Sys_Deal_Log Set State = '" + logState + "', Comments = '" + logComments + "', Deal_Times = Deal_Times + 1 Where Deal_Type = 'SmsBatchRequest' And Rec_Id = '" + batch_id + "'";
                    int[] dataresult = eliteBean.updateBatch(data, "dataSource");

                    return "{\"msg\": \"请求接口失败！\",\"code\": -1}";

                }
            } else if (datafrom.equals("1")) {
                //客户分组取数据
                String[] table = tbname.split(",");
                def sqls = 0;
                def messages = 0;
                for (i = 0; i < table.length; i++) {
                    sqls = eliteBean.update("insert into sms_send_sync(rec_guid,batch_id,sms_id,sk_invpty,invpty_name,mobile_phone,sms_content,createdate) select sysguid,'" + batch_id + "','" + sms_id + "',sk_invpty,invpty_name,mobile_phone,replace('" + content + "','[c_custname]',invpty_name),sysdate from " + table[i] + " where mobile_phone is not null", "dataSource");
                    messages = messages + sqls;
                };
                String[] data = new String[2];
                data[0] = "update sms_send_batch set state=1,requesttime=sysdate,acceptdate=sysdate,comments='执行成功',messages=" + messages + " where batch_id='" + batch_id + "'";
                data[1] = "update sms_template set lastsendtime=sysdate,batch_no='" + batch_id + "' where sms_id='" + sms_id + "'";
                int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                return "{\"msg\": \"请求接口成功！\",\"code\": 1}"
            }
        } catch (Exception e) {
            log.error("ErrorMessage:", e);
            return "{\"msg\": \"请求接口失败！\",\"code\": -1}"
        }
    }
    //判断当前时间为周几
    public static int dayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }
}